<template>
  <div class="patient-info-page">
    <van-notice-bar
      wrapable
      :scrollable="false"
      :text="noticeText"
    />

    <div class="flex1">
      <div class="visitinfo" v-if="!isUserInfo">
        当前所在科室：{{ currentDept.hospitalName }} {{ currentDept.departmentName }} <br>
        本次就诊扫码时间：{{ scanTime }}
      </div>
      <template v-for="(item, index) in patientInfo" :key="index">
        <template v-if="item.isShow">
          <InfoItem
            :ref="setInfoItemRef"
            :item-data="item"
          />
        </template>
      </template>
    </div>
    <div class="patient-info-btn">
      <van-button
        block
        type="success"
        @click="onSubmit"
      >
        保存
      </van-button>
    </div>
  </div>
</template>

<script>
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { Toast } from 'vant';
import { useUserInfo, useCurrentDeptInfo } from '@/hooks/store';
import { useService } from '@/utils/services';
import process from '@/logic/process';

import { USER_INFO_DATA, VISIT_INFO_DATA } from '../patient-info/model';
import InfoItem from '../patient-info/components/InfoItem';

export default {
  components: {
    InfoItem
  },
  setup() {
    const userInfo = useUserInfo();
    const currentDept = useCurrentDeptInfo();
    const actions = useService();

    const route = useRoute();

    const isUserInfo = route.query.type == 1;

    const noticeText = isUserInfo
      ? '为方便接收全方位的护理服务，请确认您的真实信息。'
      : '以下是您本次就诊信息';
    const configs = isUserInfo ? USER_INFO_DATA : VISIT_INFO_DATA;

    onMounted(() => {
      document.title = isUserInfo ? '个人信息' : '就诊信息';
    });

    const scanTime = ref();

    const patientInfo = ref([]);
    actions.hos.getPatientInfo().then((info) => {
      let result = { ...info.userInfo, ...info.visitInfo };
      scanTime.value = info.userInfo.scanTime;

      patientInfo.value = configs
        .filter((item) => item.isShow)
        .map((item) => {
          // 受教育水平 与患者关系
          if (['educationLevel', 'patientFormRelationWithPatient'].includes(item.field)) {
            item.value = item.options.find((option) => option.id == result[item.field])?.text || '';
          } else if (['marks'].includes(item.field)) {
            // 标记组
            item.value = result[item.field].length
              ? result[item.field]?.map((item) => item.name)?.join(',') || ''
              : '';
            item.id = result[item.field].map((item) => item.markId) || [];
          } else {
            item.value = result[item.field];
          }
          return item;
        });
    });

    const infoItemRef = ref([]);
    const setInfoItemRef = (el) => {
      el && infoItemRef.value.push(el);
    };

    const onSubmit = () => {
      let isPass = patientInfo.value.every((item, index) => {
        if (item.isRequire && !infoItemRef.value[index].currentValue.value) {
          Toast(`${item.label}不能为空`);
          return false;
        }
        return true;
      });

      if (!isPass) return;

      const resultData = {};
      patientInfo.value.forEach((item, index) => {
        resultData[item.field] =
          infoItemRef.value[index].currentValue.id ?? infoItemRef.value[index].currentValue.value;
        //默认进来直接保存没值
        if (item.field == 'patientFormRelationWithPatient') {
          item.options.forEach((val) => {
            if (val.text == infoItemRef.value[index].currentValue.value) {
              resultData[item.field] = infoItemRef.value[index].currentValue.id;
            }
          });
        }
      });
      const toast = Toast.loading({
        duration: 0,
        forbidClick: true,
        message: '保存中...'
      });
      actions.hos
        .setPatientInfo(resultData)
        .then(() => {
          Toast.success('保存成功');
        })
        .catch(() => {
          Toast.fail('保存失败');
        })
        .finally(() => {
          toast.clear();
        });
    };

    return {
      onSubmit,
      patientInfo,
      infoItemRef,
      setInfoItemRef,
      userInfo,
      isUserInfo,
      noticeText,
      currentDept,
      scanTime
    };
  }
};
</script>

<style lang="scss" scoped>
.patient-info-page {
  background: #fff;
  min-height: 100vh;
}
.bed-info {
  padding: 32px 0 32px 32px;

  font-size: 30px;
  font-weight: 400;
  color: #777b8f;
  line-height: 52px;

  .bed-num {
    color: #373d52;
    font-size: 36px;
    margin-left: 10px;
  }
}
.patient-info-btn {
  margin: auto;
  margin-top: 80px;
  padding-bottom: 80px;
  width: 80%;
}

.visitinfo {
  padding: 26px 32px;
  font-size: 30px;
  font-weight: 400;
  color: #777b8f;
  line-height: 42px;
}
</style>